package com.lcifn.zk.console.support;

import com.google.common.base.Charsets;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.data.Stat;

import java.nio.charset.Charset;
import java.util.List;

/**
 * curator zk session impl
 * @author LC
 * @date 2020/6/16 20:15
 */
public class CuratorZkSession extends AbstractZkSession implements ZkSession{

    private CuratorFramework client;

    public CuratorZkSession(CuratorFramework client) {
        this.client = client;
    }

    /**
     * 查询zk节点状态信息
     *
     * @param path
     * @return
     */
    @Override
    public Stat statNode(String path) throws Exception{
        Stat stat = client.checkExists().forPath(path);
        return stat;
    }

    /**
     * 获取节点内容
     *
     * @param path
     * @return
     */
    @Override
    public String getNodeData(String path) throws Exception{
        byte[] bytes = client.getData().forPath(path);
        return bytes == null ? null : new String(bytes);
    }

    /**
     * 获取子节点路径
     *
     * @param path
     * @return
     */
    @Override
    public List<String> childNode(String path) throws Exception{
        List<String> childrenNodePath = client.getChildren().forPath(path);
        return childrenNodePath;
    }

    /**
     * 创建节点
     *
     * @param path
     * @param data
     * @return
     */
    @Override
    public String createNode(String path, String data) throws Exception{
        String result = null;
        if (statNode(path) == null) {
            result = client.create().forPath(path, data.getBytes(Charsets.UTF_8));
        }
        return result;
    }
}
